package com.haojiang.mh.widget;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.widget.EditText;

import androidx.appcompat.widget.AppCompatEditText;

import com.haojiang.mh.R;
import com.haojiang.mh.utils.SizeUtil;

/**
 * 自定义下划线输入文本
 * <p>
 * Created by ZapFive on 2019-05-25.
 * <p>
 * wuzhuang@mirahome.me
 */
public class CustomUnderlineEditText extends AppCompatEditText {

    private Paint mPaint; // 画笔
    // 分割线变量
    private int lineColor_click, lineColor_normal;// 点击时 & 未点击颜色
    private int color;
    private int linePosition;

    public CustomUnderlineEditText(Context context) {
        super(context);
        init(context);
    }

    public CustomUnderlineEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context);
    }

    public CustomUnderlineEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context);
    }

    private void init(Context context) {// 1. 设置画笔
        lineColor_click = getResources().getColor(R.color.purple_3);
        lineColor_normal = getResources().getColor(R.color.grey_2);

        mPaint = new Paint();
        mPaint.setStrokeWidth(SizeUtil.dp2px(context, 1)); // 分割线粗细
        mPaint.setColor(lineColor_normal); // 分割线默认颜色 = 灰色

        linePosition = SizeUtil.dp2px(context, 1);

        // 消除自带下划线
        setBackgroundDrawable(null);
    }

    /**
     * 更改下划线颜色
     */
    private void setDeleteIconVisible(boolean focused) {
        color = focused ? lineColor_click : lineColor_normal;
        mPaint.setColor(color);
        invalidate();
    }

    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
        setDeleteIconVisible(focused);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        // 绘制分割线
        // 需要考虑：当输入长度超过输入框时，所画的线需要跟随着延伸
        // 解决方案：线的长度 = 控件长度 + 延伸后的长度
        int x = this.getScrollX(); // 获取延伸后的长度
        int w = this.getMeasuredWidth(); // 获取控件长度

        // 传入参数时，线的长度 = 控件长度 + 延伸后的长度
        canvas.drawLine(0, this.getMeasuredHeight() - linePosition, w + x,
                this.getMeasuredHeight() - linePosition, mPaint);

    }

}
